package com.robot.mvvm.vm.work

import android.app.Application
import androidx.databinding.ObservableField
import api.IotServiceFactory
import api.UserServiceFactory
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.model.BasePageBean
import com.robot.base.model.PersonDataDTOBean
import com.robot.base.model.QuestionDataDTOBean
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import me.goldze.mvvmhabit.http.BaseResponse

class SafetyViewModel(application: Application) : GLBaseViewModel(application) {

    var pageNo = 1
    var pageSize = 20
    var name = ObservableField<String>()

    val uc = UiChangeEvent()

    class UiChangeEvent {
        val refreshEvent = SingleLiveEvent<Int>()
        val refreshDataEvent = SingleLiveEvent<List<PersonDataDTOBean>>()
    }

    fun refresh() {
        pageNo = 1
        getSafetyPersonPageList()
    }

    fun loadNext() {
        pageNo++
        getSafetyPersonPageList()
    }

    fun getSafetyPersonPageList() {
        showLoadingDialog()

        UserServiceFactory.getSafetyPersonPageList(
            mapOf(
                "limit" to "$pageSize",
                "page" to "$pageNo",
                "personName" to (name.get() ?: "")
            )
        ).subscribe(object :
            AbstractViewModelSubscriber<BaseResponse<BasePageBean<PersonDataDTOBean>>>(this) {
            override fun onNext(t: BaseResponse<BasePageBean<PersonDataDTOBean>>) {
                dismissLoadingDialog()
                if (t.data != null) {
                    uc.refreshEvent.postValue(
                        if (t.data.hasNextPage == true) {
                            0
                        } else {
                            1
                        }
                    )
                    uc.refreshDataEvent.postValue(t.data.list)
                } else {
                    uc.refreshEvent.postValue(1)
                }
            }

            override fun onError(e: Throwable) {
                super.onError(e)
                uc.refreshEvent.postValue(0)
            }
        })
    }
}